//   Copyright 2010 Shantanu Shah<shantanus@gmail.com>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package com.shansense.coretimer;

import java.util.Date;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.format.DateFormat;
import android.widget.Toast;

public class ChangeModeUtil {

  /**
   * Broadcast receiver is expected to remain disabled for this amount of time.
   */
  public static final int BROADCAST_RECEIVER_DISABLED_TIME = (1000 * 5);
  
  /**
   * Preference value id. This specifies when we entered the mode, so that the receiver will
   * know whether to skip an intent if it's too close to this.
   */
  public static final String DISABLED_TIME_MS = "DISABLE_TIME_MS";

  private static final String MSG_CANCEL_PREVIOUS = "Canceling old timers, if any";

  /**
   * Set the timer and show notification.
   * millis may be 0, in which case, all notifications are cleared.
   * @param plugin
   * @param millis
   */
  public static void setTimer(ChangeModePlugin plugin, long millis) {
    Context context = plugin.getActivity();
    if (millis != 0) {
      AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
      PendingIntent pendingIntent = PendingIntent.getService(
          context,
          0 /* req code, unused */,
          plugin.getServiceIntent(),
          PendingIntent.FLAG_ONE_SHOT);
      alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis, pendingIntent);

    
      disableReceiver(plugin);  // to prevent self triggering, receiver will re-enable itself.
      plugin.enterMode();

      notifyEndTime(plugin, millis);
     
    } else {
      Toast.makeText(context, MSG_CANCEL_PREVIOUS, Toast.LENGTH_SHORT).show();
      plugin.leaveModeAndClearNotifications();
    }
  }

  /**
   * Save preferences for next invocation.
   * @param plugin
   * @param savedMillis - existing millis. values may be 0.
   * @param curMillis - current time chosen by the user.
   */
  public static void savePreferences(ChangeModePlugin plugin, long[] savedMillis, long curMillis) {
    final String appName = plugin.getAppName();
    SharedPreferences settings = plugin.getActivity().getSharedPreferences(appName, 0 /* default */);
    Editor editor = settings.edit();
      
    for (int i=1; i<AbsChangeModeTimer.PREF_SAVED_TIME.length; i++) {
      if (savedMillis[i-1] == curMillis) {  // TODO use some data structure with contains()  
        return;  // One of the saved values, no need to save.
      }
      editor.putLong(AbsChangeModeTimer.PREF_SAVED_TIME[i], savedMillis[i-1]);
    }
    editor.putLong(AbsChangeModeTimer.PREF_SAVED_TIME[0], curMillis);
    
    int tabIndex;
    if ((tabIndex = plugin.getTabIndexIfPresent()) >= 0) {
    	editor.putInt(AbsChangeModeTimer.PREF_TAB_INDEX, tabIndex);	
    }
    
    editor.commit();
  }
  
  private static void disableReceiver(ChangeModePlugin plugin) {
    final String appName = plugin.getAppName();
    SharedPreferences settings = plugin.getActivity().getSharedPreferences(
        appName, 0 /* default */);
    Editor editor = settings.edit();
      
    editor.putLong(ChangeModeUtil.DISABLED_TIME_MS, System.currentTimeMillis());
    editor.commit();
  }
  
  private static void notifyEndTime(ChangeModePlugin plugin, long time) {
    final Context context = plugin.getActivity();
    java.text.DateFormat format = DateFormat.getTimeFormat(context);
    String notifString = plugin.getNotificationString() + " "
        + format.format(new Date(System.currentTimeMillis() + time));
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = new Notification(plugin.getNotificationIcon(), notifString,
        System.currentTimeMillis());
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    Intent notificationIntent = plugin.getNotificationIntent();
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0 /* content */,
        notificationIntent, Notification.FLAG_NO_CLEAR);

    notification.setLatestEventInfo(context, plugin.getAppName(), notifString, contentIntent);
    nm.notify(plugin.getNotificationIcon() /* hack, but fine */, notification);
  }

}
